package com.example.novel.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.novel.domain.Book;
import com.example.novel.domain.Collect;
import com.example.novel.domain.Result;
import com.example.novel.service.BookService;
import com.example.novel.service.CollectService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

//收藏书架的增，删，查方法
@Controller
@RequestMapping("/collect")
public class CollectController {
    @Resource
    private CollectService collectService;

    @Resource
    private BookService bookService;
    @ResponseBody
    @RequestMapping("/getByIdList/{userId}")//获取收藏列表(查找)
    public Result getByIdList(@PathVariable String userId) {
        List<Collect> collectUsers = collectService.query().eq("user_id", userId).list();

        // 提取 collectUsers 中的 id 列表
        List<Integer> collectBookIds =  collectUsers.stream()
                .map(Collect::getBookId) // 假设 Collect 类有一个 getId 方法
                .collect(Collectors.toList());

        // 获取书籍列表
        List<Book> books = bookService.query().in("id", collectBookIds).list();


        Result result = new Result();
        result.setData(books);
        return result;
    }
    @ResponseBody
    @RequestMapping("/addByIdList/{userId}/{bookId}")//添加收藏,收藏书籍到书架
    public Result addByIdList(@PathVariable String userId, @PathVariable String bookId) {
        Result result = new Result();
        Collect collect = new Collect();
        collect.setUserId(Integer.parseInt(userId));
        collect.setBookId(Integer.parseInt(bookId));
        collectService.save(collect);//调用collectService的save保存方法
        return result;
    }

    @ResponseBody
    @RequestMapping("/deleteById/{userId}/{bookId}")//删除收藏
    public Result deleteById(@PathVariable String userId, @PathVariable String bookId) {
        Result result = new Result();
        LambdaQueryWrapper<Collect> wrapper = new LambdaQueryWrapper<Collect>()
               .eq(Collect::getUserId, userId)
               .eq(Collect::getBookId, bookId);
        collectService.remove(wrapper);
        return result;
    }
}
